package reviewAlgorithms.search;

import java.util.Arrays;

public class NumSquares2 {
    public static void main(String[] args) {
        System.out.println(numSquares(184));
    }

    /**
     * 动态规划
     * @param n
     * @return
     */
    public static int numSquares(int n) {
        if (n < 1){
            return 0;
        }
        int[] dp = new int[n + 1];
        Arrays.fill(dp, Integer.MAX_VALUE);
        dp[0] = 0;
        int maxNum = (int) Math.sqrt(n);
        int[] squares = new int[maxNum];
        for (int i = 0; i < maxNum; i++) {
            squares[i] = (i + 1) * (i + 1);
        }

        for (int i = 1; i <= n; i++) {
            for (int j = 0; j < maxNum; j++) {
                if (i < squares[j]){
                    break;
                }
                dp[i] = Math.min(dp[i],dp[i - squares[j]] + 1);
            }
        }

        return dp[n];
    }
}
